const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const { glob } = require('glob');
const cliProgress = require('cli-progress');
const chalk = require('chalk');

async function compressImages(dirPath) {
  try {
    // 获取所有图片文件
    const files = await glob('**/*.{jpg,jpeg,png}', { cwd: dirPath, absolute: true });
    
    if (files.length === 0) {
      console.log(chalk.yellow('未找到任何图片文件'));
      return;
    }

    console.log(chalk.blue(`找到 ${files.length} 个图片文件`));

    // 创建进度条
    const progressBar = new cliProgress.SingleBar({
      format: '压缩进度 |' + chalk.cyan('{bar}') + '| {percentage}% || {value}/{total} 个文件',
      barCompleteChar: '\u2588',
      barIncompleteChar: '\u2591',
    });

    progressBar.start(files.length, 0);

    let totalOriginalSize = 0;
    let totalCompressedSize = 0;

    // 处理每个文件
    for (const file of files) {
      const stats = fs.statSync(file);
      totalOriginalSize += stats.size;

      // 压缩图片
      await sharp(file)
        .jpeg({ quality: 80 })
        .toBuffer()
        .then(async (data) => {
          totalCompressedSize += data.length;
          await fs.promises.writeFile(file, data);
          progressBar.increment();
        })
        .catch((err) => {
          console.error(chalk.red(`处理文件 ${file} 时出错:`, err));
        });
    }

    progressBar.stop();

    // 显示压缩结果
    const originalSizeMB = (totalOriginalSize / 1024 / 1024).toFixed(2);
    const compressedSizeMB = (totalCompressedSize / 1024 / 1024).toFixed(2);
    const savedSizeMB = (originalSizeMB - compressedSizeMB).toFixed(2);
    const compressionRatio = ((1 - totalCompressedSize / totalOriginalSize) * 100).toFixed(1);

    console.log(chalk.green('\n压缩完成！'));
    console.log(chalk.white(`原始大小: ${originalSizeMB} MB`));
    console.log(chalk.white(`压缩后大小: ${compressedSizeMB} MB`));
    console.log(chalk.white(`节省空间: ${savedSizeMB} MB (${compressionRatio}%)`));

  } catch (error) {
    console.error(chalk.red('发生错误:', error));
  }
}

// 获取命令行参数中的目录路径
const directoryPath = process.argv[2];

if (!directoryPath) {
  console.log(chalk.red('请提供要压缩的图片目录路径'));
  console.log(chalk.yellow('使用方法: node index.js <目录路径>'));
  process.exit(1);
}

if (!fs.existsSync(directoryPath)) {
  console.log(chalk.red('指定的目录不存在'));
  process.exit(1);
}

compressImages(directoryPath);